# -*-coding:utf-8 -*-
from django.db import models
from django.core.exceptions import ValidationError
from datetime import date, timedelta, datetime
from django.utils import timezone


class WatchDutyQuerySet(models.QuerySet):

    def today(self):
        return self.filter(date_start__lte=date.today(), type=WatchDuty.DUTY_DAY).order_by("date_start")

    def current_week(self):
        start_date = datetime.now() - timedelta(days=date.today().isoweekday())
        end_date = start_date + timedelta(days=7)
        return self.filter(date_start__lte=start_date.date(), date_start__gte=end_date.date(), type=WatchDuty.DUTY_WEEK).order_by("date_start")

    def current_month(self):
        start_date = date.today()
        start_date = date(year=start_date.year, month=start_date.month, day=1)
        return self.filter(date_start__lte=start_date, type=WatchDuty.DUTY_MONTH).order_by("date_start")


class WatchDuty(models.Model):
    DUTY_DAY = "D"
    DUTY_WEEK = "W"
    DUTY_MONTH = "M"
    DUTY_TYPE = ((DUTY_DAY, u'日'), (DUTY_WEEK, u'周'), (DUTY_MONTH, u'月'),)
    createdat = models.DateTimeField('创建时间', default=timezone.now())
    department = models.ForeignKey('org.Department', null=True, verbose_name="值班部门", on_delete=models.CASCADE)
    who = models.ForeignKey('org.Person', verbose_name=u"值班人员", db_index=True, on_delete=models.CASCADE)
    is_leader = models.NullBooleanField(u'是否领导', null=True)
    job = models.CharField(u'职务', max_length=50, null=True)
    mobile = models.CharField(u'联系电话', max_length=21, null=True, help_text=u'默认为值班人员登记的联系电话')
    date_start = models.DateField(u'开始日期', default=timezone.now())
    date_end = models.DateField(u'结束日期',  null=True)
    type = models.CharField(u'类型', max_length=1, choices=DUTY_TYPE, default='W')
    memo = models.CharField(u'备注', max_length=255, null=True, blank=True)

    objects = WatchDutyQuerySet.as_manager()

    def clean(self):
        if not self.department:
            self.department = self.who.department
        if self.type == 'D' and self.date_end is None:
            self.date_end = self.date_start + timedelta(days=1)
        if self.type == 'W':
            if self.date_start.isoweekday() != 1:
                raise ValidationError({'date_start': u'开始日期必须是从周一开始'})
            self.date_end = self.date_start + timedelta(days=7)
        if self.type == 'M':
            if self.date_start.day != 1:
                raise ValidationError({'date_start': u'开始日期必须是从每月的第一天开始'})
            import calendar
            m, d = calendar.monthrange(self.date_start.year, self.date_start.month)
            self.date_end = self.date_start + timedelta(days=d)
        if not self.mobile:
            self.mobile = self.who.mobile

        if not self.is_leader:
            self.is_leader = self.who.is_leader
        if not self.job:
            self.job = self.who.job

    def __str__(self):
        return '%s 值班' % self.date_start

    def __unicode__(self):
        return self.__str__()

    def get_department_name(self):
        return u"%s" % self.department

    def get_who_name(self):
        return u"%s" % self.who

    def get_who_thumbnai100x100(self):
        if self.who:
            return self.who.get_thumbnai100x100()
        else:
            return None

    class Meta:
        verbose_name_plural = verbose_name = "值班排版表"


class WhereTo(models.Model):
    createdat = models.DateTimeField('创建时间', default=timezone.now(), editable=False)
    department = models.ForeignKey('org.Department', verbose_name="所在部门", null=True, blank=True, on_delete=models.SET_NULL, help_text=u'默认为外出人员当时所在的部门')
    who = models.ForeignKey('org.Person', verbose_name=u"外出人员", db_index=True, on_delete=models.CASCADE)
    is_leader = models.BooleanField(u'是否领导', default=False, help_text=u'默认为外出人员当时登记的信息')
    job = models.CharField(u'职务', max_length=50, blank=True, null=True, help_text=u'默认为外出人员当时登记的信息')
    mobile = models.CharField(u'联系电话', max_length=21, blank=True, null=True, help_text=u'默认为外出人员当时登记的联系电话')
    reason = models.CharField(u'外出原由', max_length=50, blank=True, null=True, help_text=u'例如：开户，客户拜访等')
    leave_time = models.DateTimeField(u'离开时间', default=timezone.now(), help_text=u'填写离开的时间')
    back_time = models.DateTimeField(u'（预计）到岗时间', blank=True, null=True)
    memo = models.CharField(u'备注', max_length=255, null=True, blank=True)

    def __str__(self):
        return '%s 去向' % self.who

    def __unicode__(self):
        return self.__str__()

    def get_department_name(self):
        return u"%s" % self.department

    def get_who_name(self):
        return u"%s" % self.who

    def get_who_thumbnai100x100(self):
        if self.who:
            return self.who.get_thumbnai100x100()
        else:
            return None

    def clean(self):
        if not self.department:
            self.department = self.who.department
        if not self.is_leader:
            self.is_leader = self.who.is_leader
        if not self.job:
            self.job = self.who.job
        if not self.mobile:
            self.mobile = self.who.mobile

    class Meta:
        verbose_name_plural = verbose_name = "去向公示"
